<template>
  <div class="app-container">
    <!-- 概览卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-device">
            <i class="el-icon-s-data card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">设备总数</div>
            <div class="card-panel-num">{{ overview.totalDevices }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-stable">
            <i class="el-icon-success card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">稳定设备</div>
            <div class="card-panel-num">{{ overview.stableDevices }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-unstable">
            <i class="el-icon-warning card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">不稳定设备</div>
            <div class="card-panel-num">{{ overview.unstableDevices }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-rate">
            <i class="el-icon-pie-chart card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">稳定率</div>
            <div class="card-panel-num">{{ overview.stabilityRate }}%</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 设备网络状态表格 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-monitor"></i> 设备网络监控</span>
        <div style="float: right;">
          <el-button size="mini" @click="refreshData" :loading="loading">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
          <el-button size="mini" type="danger" @click="clearAllData" v-hasPermi="['business:network:manage']">
            <i class="el-icon-delete"></i> 清空数据
          </el-button>
        </div>
      </div>

      <el-table v-loading="loading" :data="deviceList" style="width: 100%" size="small">
        <el-table-column label="设备编码" prop="deviceSN" width="120" />
        <el-table-column label="IP地址" prop="ipAddress" width="140" align="center" />
        <el-table-column label="端口" prop="port" width="80" align="center" />
        <el-table-column label="稳定状态" width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isStable ? 'success' : 'danger'" size="mini">
              {{ scope.row.isStable ? '稳定' : '不稳定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="网络质量" width="100" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="getQualityType(scope.row.qualityLevel)" 
              size="mini"
            >
              {{ scope.row.qualityLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="成功率" width="100" align="center">
          <template slot-scope="scope">
            <div class="progress-wrapper">
              <el-progress 
                :percentage="scope.row.successRate" 
                :color="getSuccessRateColor(scope.row.successRate)"
                :show-text="false"
                :stroke-width="8"
              ></el-progress>
              <span class="progress-text">{{ scope.row.successRate }}%</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="平均响应时间" width="100" align="center">
          <template slot-scope="scope">
            <span :class="{'slow-response': scope.row.averageResponseTime > 1000}">
              {{ scope.row.averageResponseTime }}ms
            </span>
          </template>
        </el-table-column>
        <el-table-column label="抖动" width="100" align="center">
          <template slot-scope="scope">
            <span :class="{'high-jitter': scope.row.responseTimeJitter > 100}">
              {{ scope.row.responseTimeJitter }}ms
            </span>
          </template>
        </el-table-column>
        <el-table-column label="总操作数" width="100" align="center" prop="totalAttempts" />
        <el-table-column label="失败次数" width="100" align="center">
          <template slot-scope="scope">
            <span :class="{'high-failure': scope.row.failureCount > 10}">
              {{ scope.row.failureCount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="监控时长" width="120" align="center">
          <template slot-scope="scope">
            {{ formatDuration(scope.row.monitoringDuration) }}
          </template>
        </el-table-column>
        <el-table-column label="最后失败时间" width="150" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.lastFailureTime > 0">
              {{ parseTime(scope.row.lastFailureTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
            </span>
            <span v-else style="color: #67C23A;">从未失败</span>
          </template>
        </el-table-column>
        <el-table-column label="不稳定原因" min-width="120">
          <template slot-scope="scope">
            <span v-if="!scope.row.isStable" style="color: #F56C6C;">
              {{ scope.row.stabilityReason }}
            </span>
            <span v-else style="color: #67C23A;">正常</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="text" 
              @click="showDeviceDetail(scope.row)"
            >
              <i class="el-icon-view"></i> 详情
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="clearDeviceData(scope.row.deviceSN)"
              v-hasPermi="['business:network:manage']"
            >
              <i class="el-icon-delete"></i> 清除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 设备详情对话框 -->
    <el-dialog title="设备网络详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="selectedDevice">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备编码">{{ selectedDevice.deviceSN }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ selectedDevice.ipAddress || '-' }}</el-descriptions-item>
          <el-descriptions-item label="端口">{{ selectedDevice.port || '-' }}</el-descriptions-item>
          <el-descriptions-item label="稳定状态">
            <el-tag :type="selectedDevice.isStable ? 'success' : 'danger'">
              {{ selectedDevice.isStable ? '稳定' : '不稳定' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="网络质量">
            <el-tag :type="getQualityType(selectedDevice.qualityLevel)">
              {{ selectedDevice.qualityLevel }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="成功率">{{ selectedDevice.successRate }}%</el-descriptions-item>
          <el-descriptions-item label="平均响应时间">{{ selectedDevice.averageResponseTime }}ms</el-descriptions-item>
          <el-descriptions-item label="响应时间抖动">{{ selectedDevice.responseTimeJitter }}ms</el-descriptions-item>
          <el-descriptions-item label="总操作数">{{ selectedDevice.totalAttempts }}</el-descriptions-item>
          <el-descriptions-item label="成功操作数">{{ selectedDevice.successfulAttempts }}</el-descriptions-item>
          <el-descriptions-item label="失败次数">{{ selectedDevice.failureCount }}</el-descriptions-item>
          <el-descriptions-item label="距离上次失败">{{ formatDuration(selectedDevice.timeSinceLastFailure) }}</el-descriptions-item>
          <el-descriptions-item label="监控开始时间">
            {{ parseTime(selectedDevice.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-descriptions-item>
          <el-descriptions-item label="监控时长">{{ formatDuration(selectedDevice.monitoringDuration) }}</el-descriptions-item>
        </el-descriptions>
        
        <div v-if="!selectedDevice.isStable" style="margin-top: 20px;">
          <el-alert
            title="稳定性问题"
            :description="selectedDevice.stabilityReason"
            type="warning"
            show-icon
            :closable="false">
          </el-alert>
        </div>
      </div>
    </el-dialog>

    <!-- 监控配置对话框 -->
    <el-dialog title="监控配置" :visible.sync="configDialogVisible" width="600px">
      <div v-if="monitorConfig">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="稳定成功率阈值">{{ monitorConfig.stableSuccessRate }}</el-descriptions-item>
          <el-descriptions-item label="稳定平均响应时间阈值">{{ monitorConfig.stableAvgResponseTime }}</el-descriptions-item>
          <el-descriptions-item label="稳定无失败时间阈值">{{ monitorConfig.stableNoFailureTime }}</el-descriptions-item>
          <el-descriptions-item label="最小样本数">{{ monitorConfig.minSamples }}</el-descriptions-item>
          <el-descriptions-item label="最大响应时间样本数">{{ monitorConfig.maxResponseSamples }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{ monitorConfig.description }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getAllDevicesNetworkOverview, 
  getDeviceNetworkStats, 
  getBatchDeviceStats,
  clearDeviceStats, 
  clearAllStats, 
  getMonitorConfig 
} from "@/api/business/network"

export default {
  name: "NetworkMonitor",
  data() {
    return {
      loading: false,
      // 概览数据
      overview: {
        totalDevices: 0,
        stableDevices: 0,
        unstableDevices: 0,
        stabilityRate: 0
      },
      // 设备列表
      deviceList: [],
      // 对话框状态
      detailDialogVisible: false,
      configDialogVisible: false,
      // 选中的设备
      selectedDevice: null,
      // 监控配置
      monitorConfig: null,
      // 定时器
      refreshTimer: null
    }
  },
  created() {
    this.loadData()
    this.loadMonitorConfig()
    // 每30秒自动刷新一次
    this.refreshTimer = setInterval(() => {
      this.loadData()
    }, 30000)
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  },
  methods: {
    /** 加载数据 */
    async loadData() {
      this.loading = true
      try {
        // 获取概览数据
        const overviewResponse = await getAllDevicesNetworkOverview()
        this.overview = overviewResponse.data
        
        // 获取设备列表详细数据
        if (this.overview.deviceStatus) {
          const deviceSNs = Object.keys(this.overview.deviceStatus)
          if (deviceSNs.length > 0) {
            const batchResponse = await getBatchDeviceStats(deviceSNs)
            this.deviceList = Object.keys(batchResponse.data).map(deviceSN => ({
              deviceSN,
              ...batchResponse.data[deviceSN].stats
            }))
          } else {
            this.deviceList = []
          }
        }
      } catch (error) {
        this.$message.error('加载监控数据失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    /** 加载监控配置 */
    async loadMonitorConfig() {
      try {
        const response = await getMonitorConfig()
        this.monitorConfig = response.data
      } catch (error) {
        console.error('加载监控配置失败', error)
      }
    },

    /** 刷新数据 */
    refreshData() {
      this.loadData()
    },

    /** 显示设备详情 */
    async showDeviceDetail(device) {
      try {
        const response = await getDeviceNetworkStats(device.deviceSN)
        this.selectedDevice = response.data
        this.detailDialogVisible = true
      } catch (error) {
        this.$message.error('获取设备详情失败')
      }
    },

    /** 清除设备数据 */
    async clearDeviceData(deviceSN) {
      try {
        await this.$confirm(`确认清除设备 ${deviceSN} 的监控数据吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await clearDeviceStats(deviceSN)
        this.$message.success('清除成功')
        this.loadData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('清除失败')
        }
      }
    },

    /** 清除所有数据 */
    async clearAllData() {
      try {
        await this.$confirm('确认清除所有设备的监控数据吗？此操作不可恢复！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await clearAllStats()
        this.$message.success('清除成功')
        this.loadData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('清除失败')
        }
      }
    },

    /** 获取质量等级类型 */
    getQualityType(quality) {
      switch (quality) {
        case '优秀': return 'success'
        case '良好': return 'success' 
        case '一般': return 'warning'
        case '较差': return 'danger'
        default: return 'info'
      }
    },

    /** 获取成功率颜色 */
    getSuccessRateColor(rate) {
      if (rate >= 95) return '#67C23A'
      if (rate >= 90) return '#E6A23C'
      return '#F56C6C'
    },

    /** 格式化时长 */
    formatDuration(milliseconds) {
      if (!milliseconds || milliseconds < 0) return '0秒'
      
      const seconds = Math.floor(milliseconds / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)
      const days = Math.floor(hours / 24)
      
      if (days > 0) {
        return `${days}天${hours % 24}小时`
      } else if (hours > 0) {
        return `${hours}小时${minutes % 60}分钟`
      } else if (minutes > 0) {
        return `${minutes}分钟${seconds % 60}秒`
      } else {
        return `${seconds}秒`
      }
    }
  }
}
</script>

<style scoped>
.panel-group {
  margin-top: 18px;
}

.card-panel-col {
  margin-bottom: 32px;
}

.card-panel {
  height: 108px;
  cursor: pointer;
  font-size: 12px;
  position: relative;
  overflow: hidden;
  color: #666;
  background: #fff;
  box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
  border-color: rgba(0, 0, 0, .05);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.card-panel-icon-wrapper {
  float: left;
  overflow: hidden;
  padding: 16px;
  transition: all 0.38s ease-out;
  border-radius: 6px;
}

.card-panel-icon {
  float: left;
  font-size: 48px;
}

.card-panel-description {
  float: right;
  font-weight: bold;
  margin: 26px;
  margin-left: 0px;
  text-align: right;
}

.card-panel-text {
  line-height: 18px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 16px;
  margin-bottom: 12px;
}

.card-panel-num {
  font-size: 30px;
  color: rgba(0, 0, 0, 0.85);
}

.icon-device {
  color: #40c9c6;
}

.icon-stable {
  color: #67C23A;
}

.icon-unstable {
  color: #F56C6C;
}

.icon-rate {
  color: #1890ff;
}

.progress-wrapper {
  display: flex;
  align-items: center;
}

.progress-text {
  margin-left: 10px;
  font-size: 12px;
  min-width: 40px;
}

.slow-response {
  color: #F56C6C;
  font-weight: bold;
}

.high-jitter {
  color: #E6A23C;
  font-weight: bold;
}

.high-failure {
  color: #F56C6C;
  font-weight: bold;
}
</style>
